package cn.edu.scnu.entry.controller;

import cn.edu.scnu.entry.model.Result;
import cn.edu.scnu.entry.model.User;
import cn.edu.scnu.entry.service.RegisterService;
import cn.edu.scnu.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class RegisterController {
    @Autowired
    private RegisterService registerService;
    @PostMapping("/api/user/register")
    public Result register(@RequestBody User user)
    {
        log.info("正在注册,输入为{}",user);
        if(user.getUsername()==null|| user.getUsername().equals(""))
            return Result.error(404,"用户名不能为空");
        if(user.getPassword()==null|| user.getPassword().equals(""))
            return Result.error(404,"密码不能为空");
        if(user.getPassword().length()<6|| user.getPassword().length()>11)
            return Result.error(404,"请保证密码长度为6-11位");
        User userinfo=registerService.register(user);
        if(userinfo==null)
            return Result.error(404,"用户名已存在");
        return Result.success("注册成功",userinfo);
    }
    @PostMapping("/api/user/login")
    public Result login(@RequestBody User user)
    {
        log.info("正在登录,输入为{}",user);
        if(user.getUsername()==null|| user.getUsername().equals(""))
            return Result.error(404,"用户名不能为空");
        if(user.getPassword()==null|| user.getPassword().equals(""))
            return Result.error(404,"密码不能为空");
        User userinfo=registerService.login(user);
        if(userinfo!=null){
            //1. 生成JWT令牌
            Map<String,Object> dataMap = new HashMap<>();
            dataMap.put("id", userinfo.getId());
            dataMap.put("username", userinfo.getUsername());
            String jwt = JwtUtils.generateJwt(dataMap);
            userinfo.setToken(jwt);
            return Result.success("登录成功",userinfo);
        }
        return Result.error(404,"用户名或密码错误");
    }
}
